package cn.edu.swu.dlx;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

public class DatabaseService {

    private BasicDataSource dataSource = null;

    public void init(){
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://10.122.7.154:3306/book_store_2025");
        dataSource.setUsername("root");
        dataSource.setPassword("qwer1234");

        dataSource.setInitialSize(3);
        dataSource.setMaxTotal(6);
        dataSource.setMaxIdle(4);
        dataSource.setMinIdle(2);
        dataSource.setMaxWaitMillis(10000);
    }

    public Connection getConnection() throws Exception{
        return dataSource.getConnection();
    }

    public void closeDataSource() throws Exception{
        if(dataSource != null){
            try{dataSource.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    public List query(String sql, ResultSetVisitor visitor) throws Exception{
        try(Connection connection=this.dataSource.getConnection()){
            try(Statement statement=connection.createStatement()){
                try(ResultSet resultSet=statement.executeQuery(sql)){
                    return visitor.visit(resultSet);
                }
            }
        }
    }
}
